package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.GoodsToupiaoMapper;
import com.qianniu.napi.admin.mapper.ToupiaoLogMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.TemplatemsgActor;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class HuodongController {

    private static final Logger logger = LoggerFactory.getLogger(HuodongController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IPintuanOpenService pintuanOpenService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ToupiaoLogMapper toupiaoLogMapper;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private GoodsToupiaoMapper goodsToupiaoMapper;
    @Autowired
    private ICutpriceOpenService cutpriceOpenService;
    @Autowired
    private IJizanLogService jizanLogService;
    @Autowired
    private IChoujiangService choujiangService;

    //开团接口《针对平台型商家发起的活动》
    //营销活动暂不支持券
    @RequestMapping("/api/order/kaituan")
    @ResponseBody
    public Jinfo kaituan(Order order,
                         @RequestParam(value = "oid", required = false) Long oid,
                         @RequestParam(value = "ptoid", required = false) Long ptoid,
                         @RequestParam(value = "leaid", required = false) Long leaid,
                         @RequestParam(value = "s", required = false) String scene,
                         @RequestParam(value = "o", required = false) String ori,
                         @RequestParam(value = "tmplIds", required = false) String tmplIds,
                         HttpServletRequest req) {
        logger.debug("---------------------------------------order/kaituan=" + JSON.toJSONString(order));
        logger.debug("---------------------------------------order/cantuan tmplIds=" + tmplIds);

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价

        User user = redisService.getUser();
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        Goods goods = goodsService.selectById(order.getGid());
        logger.debug("========goods=" + JSON.toJSONString(goods));

        //生成订单
        Long uid = ObjectUtil.getUid();
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo(""));//订单
        order.setState(-1);
        order.setPrice(goods.getSaleprice());
        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);

        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);

        if (order.getRealpay().doubleValue() > 0) {
            order.setStatus(1);
        } else {
            order.setStatus(order.getGtype() == 1 ? 2 : 3);
            order.setPaytime(new Date());
        }

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        if (goods.getLeagueid() != null) order.setLeagueid(goods.getLeagueid());
        if (leaid != null) order.setLeagueid(goods.getLeagueid());
        order.setHeadimg(user.getAvatarPic());
        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        if (order.getId() == null) {
            order.setCreatetime(new Date());
        } else {
            order.setModifytime(new Date());
            order.updateById();
        }

        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);

        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        if (pstype == null) pstype = store == null ? null : store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;//自提|到店|核销
        MerchantConfig mconfig = redisService.getMconfig();
        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                logger.debug("---------------------------------------store.getPstype()=" + store.getPstype());
                pstype = store.getPstype();
                if (pstype == 4 && Strings.isNullOrEmpty(order.getAddress())) {
                    order.setAddress(store.getAddress());
                }
            } else {
                logger.debug("---------------------------------------mconfig.getPstype()=" + mconfig.getPstype());
                pstype = mconfig.getPstype();
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
            logger.debug("---------------------------------------pstype 0");
        }
        logger.debug("---------------------------------------pstype=" + pstype);
        order.setShipperMethod(pstype);

        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型

        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;
        boolean lianmeng = goods.getLeagueid() != null;

        //分享佣金计算
        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
            logger.debug("-------------------------cout=" + cout);
            logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
            //fenxiaoshu=null 分销奖励份数无限制
            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
                sharefan = goods.getShareMount().multiply(num);
                sharefanj = sharefan;
            }
        }
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        //计算活动有效时常(单位：小时)
        if (goods.getTimeout() != null && goods.getTimeout().intValue() > 0) {
            order.setEndtime(DateUtil.addHour(order.getCreatetime(), goods.getTimeout().intValue()));
        }
        order.insert();

        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }

        //订单商品
        OrderGoods og = new OrderGoods();

        og.setGid(order.getGid());

        //普通分享奖励模式
        GoodsSku goodssku = null;
        if (order.getSkuid() != null && order.getSkuid() > 0) {
            goodssku = goodsSkuService.selectById(order.getSkuid());
            og.setNumber(order.getGoodsNumber());
            og.setSaleprice(goodssku.getSaleprice());
            og.setPrice(goodssku.getPrice());
            og.setSpec(goodssku.getCharacteristic());

        } else if (order.getGid() != null && order.getGid() > 0) {

            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());


        if (order.getId() == null) {
            order.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        }


        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        //创建开团,订单支付成功之后再创建开团信息
        PintuanOpen pintuanOpen = null;
        if (ptoid == null) {
            pintuanOpen = new PintuanOpen();
            pintuanOpen.setMid(order.getMid());
            pintuanOpen.setMpid(order.getMpid());

            pintuanOpen.setCreatetime(new Date());
            pintuanOpen.setUid(order.getUid());
            pintuanOpen.setAvatarpic(user.getAvatarPic());
            pintuanOpen.setNickname(user.getNickName());

            pintuanOpen.setGid(order.getGid());
            pintuanOpen.setGoodsName(goods.getName());
            pintuanOpen.setPic(goods.getName());
            pintuanOpen.setIsGroups(1);
            pintuanOpen.setPhone(order.getPhone());

            pintuanOpen.setStatus(PTstatus.init.getVal());  //业务状态@1：进行中；2：拼团成功；0：拼团失败；
            pintuanOpen.setState(-1);  //业务状态@1：进行中；2：拼团成功；0：拼团失败；
            pintuanOpen.setStarttime(new Date());
            pintuanOpen.setEndtime(DateUtil.addDay(pintuanOpen.getStarttime(), goods.getTimeout()));//默认3天
            if (pintuanOpen.getEndtime().getTime() > goods.getEndDate().getTime()) {
                pintuanOpen.setEndtime(goods.getEndDate());
            }
            pintuanOpen.setPrice(goods.getPrice());//默认15天
            pintuanOpen.setPinprice(goods.getSaleprice());//默认15天
            pintuanOpen.setCheapprice(goods.getPrice().subtract(goods.getSaleprice()));//优惠价
            pintuanOpen.setPtotal(goods.getPtotal());//拼团数
            pintuanOpen.setPnumber(0);//已参团数
            pintuanOpen.setOid(order.getId());//已参团数
            pintuanOpen.insert();
            ptoid = pintuanOpen.getId();
        } else {
//           pintuanOpen = pintuanOpenService.selectById(ptoid);
        }

        PintuanLog pintuanLog = new PintuanLog();
        pintuanLog.setUid(order.getUid());
        pintuanLog.setMid(order.getMid());
        pintuanLog.setMpid(order.getMpid());

        pintuanLog.setPtoid(ptoid);
        pintuanLog.setPtid(order.getGid());
        pintuanLog.setGid(order.getGid());
        pintuanLog.setOid(order.getId());

        pintuanLog.setAvatarpic(user.getAvatarPic());
        pintuanLog.setNickname(user.getNickName());
        pintuanLog.setPhone(order.getPhone());
        pintuanLog.setCreatetime(new Date());
        pintuanLog.setState(-1);
        pintuanLog.setAmount(1);
        pintuanLog.setIsowner(oid == null ? 1 : 0);
        pintuanLog.insert();

        //======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));
        if (order.getRealpay().doubleValue() > 0) {
            json.setInfo(orderService.getPaymap(order, false, "在线支付拼团活动"));
        } else {
            if (order.getStatus() >= 2) {
//             processPayAccoumt(order);
                if (oid == null) {
                    PintuanOpen pt = new PintuanOpen();
                    pt.setId(ptoid);
                    pt.setStatus(PTstatus.init.getVal());
                    pt.updateById();
                } else {
                    PintuanOpen pt = pintuanOpenService.selectById(ptoid);
                    pt.setPnumber(pt.getPnumber() + 1);
                    pt.setModifier(order.getUid());
                    pt.setModifytime(new Date());
                    pt.updateById();
                }

                Goods ngoods = new Goods();
                ngoods.setId(order.getGid());
                ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);
//               if (goods.getStores() != null && goods.getStores().intValue() > 0)
//                   ngoods.setStores(goods.getStores() - 1);

                ngoods.setNumberOrders(goods.getNumberOrders() + 1);
                //拼团销售量
                ngoods.setNumberSale(goods.getNumberOrders() + order.getGoodsNumber());

                if (ngoods.getStores() != null & ngoods.getStores().longValue() > 0
                        && ngoods.getStores().longValue() <= ngoods.getNumberSale().longValue()) {
                    ngoods.setStatus(Gstatus.over.getVal());
                }

                ngoods.setModifytime(new Date());
                ngoods.setModifier(order.getUid());
                ngoods.updateById();

            } else {
                logger.debug(">>>>order unprocess logic");
                json.setInfo(order);
            }
        }

        return json;
    }

    //参团接口
    @RequestMapping("/api/order/cantuan")
    @ResponseBody
    public Jinfo cantuan(Order order,
                         @RequestParam(value = "oid", required = false) Long oid,
                         @RequestParam(value = "ptoid", required = false) Long ptoid,
                         @RequestParam(value = "leaid", required = false) Long leaid,
                         @RequestParam(value = "s", required = false) String scene,
                         @RequestParam(value = "o", required = false) String ori,
                         @RequestParam(value = "tmplIds", required = false) String tmplIds,
                         HttpServletRequest req) {
        logger.debug("------------------order/cantuan=" + JSON.toJSONString(order));
        logger.debug("----------------------------------order/cantuan tmplIds=" + tmplIds);
        PintuanOpen pto = null;
        if (oid != null && ptoid == null) {
            pto = pintuanOpenService.selectOne(new EntityWrapper<PintuanOpen>()
                    .eq("oid", oid));
            if (pto == null) {
                logger.info("------------------PintuanOpen not found for oid=" + oid);
            }
            ptoid = pto == null ? null : pto.getId();
        }
        if (ptoid != null) {
            pto = pintuanOpenService.selectOne(new EntityWrapper<PintuanOpen>()
                    .eq("id", ptoid));
            if (pto == null) {
                logger.info("------------------PintuanOpen not found for ptoid=" + ptoid);
            }
        }

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价

        User user = redisService.getUser();
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        //生成订单
        Long uid = ObjectUtil.getUid();
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo(""));//订单
        order.setState(-1);

        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);

        Goods goods = goodsService.selectById(order.getGid());
        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);

        if (order.getRealpay().doubleValue() > 0) {
            order.setStatus(1);
        } else {
            order.setStatus(order.getGtype() == 1 ? 2 : 3);
        }

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        if (goods.getLeagueid() != null) order.setLeagueid(goods.getLeagueid());
        if (leaid != null) order.setLeagueid(goods.getLeagueid());
        order.setHeadimg(user.getAvatarPic());
        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);

        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        if (pstype == null) pstype = store == null ? null : store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;//自提|到店|核销
        MerchantConfig mconfig = redisService.getMconfig();
        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                logger.debug("---------------------------------------store.getPstype()=" + store.getPstype());
                pstype = store.getPstype();
                if (pstype == 4 && Strings.isNullOrEmpty(order.getAddress())) {
                    order.setAddress(store.getAddress());
                }
            } else {
                logger.debug("---------------------------------------mconfig.getPstype()=" + mconfig.getPstype());
                pstype = mconfig.getPstype();
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
            logger.debug("---------------------------------------pstype 0");
        }
        logger.debug("---------------------------------------pstype=" + pstype);
        order.setShipperMethod(pstype);

        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型
        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;

        //分享佣金计算
        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
            logger.debug("-------------------------cout=" + cout);
            logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
            //fenxiaoshu=null 分销奖励份数无限制
            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
                sharefan = goods.getShareMount().multiply(num);
                sharefanj = sharefan;
            }
        }
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(new BigDecimal(order.getGoodsNumber()));
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(new BigDecimal(order.getGoodsNumber()));


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }

        //订单商品
        OrderGoods og = new OrderGoods();

        og.setGid(order.getGid());

        GoodsSku goodssku = null;
        if (order.getSkuid() != null && order.getSkuid() > 0) {
            goodssku = goodsSkuService.selectById(order.getSkuid());
            og.setNumber(order.getGoodsNumber());
            og.setSaleprice(goodssku.getSaleprice());
            og.setPrice(goodssku.getPrice());
            og.setSpec(goodssku.getCharacteristic());

        } else if (order.getGid() != null && order.getGid() > 0) {

            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

        if (order.getId() == null) {
            order.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        }

        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        PintuanLog pintuanLog = new PintuanLog();
        pintuanLog.setUid(order.getUid());
        pintuanLog.setMid(order.getMid());
        pintuanLog.setMpid(order.getMpid());

        pintuanLog.setPtoid(ptoid);
        pintuanLog.setPtid(order.getGid());
        pintuanLog.setGid(order.getGid());
        pintuanLog.setOid(order.getId());

        pintuanLog.setAvatarpic(user.getAvatarPic());
        pintuanLog.setNickname(user.getNickName());
        pintuanLog.setPhone(order.getPhone());

        pintuanLog.setCreatetime(new Date());
        pintuanLog.setState(-1);
        pintuanLog.setAmount(1);
        pintuanLog.setIsowner(0);
        pintuanLog.insert();

        //======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));
        if (order.getRealpay().doubleValue() > 0) {
            json.setInfo(orderService.getPaymap(order, false, "在线支付参团活动"));
        }

        return json;
    }

    //开团接口《针对平台型商家发起的活动》
    //抽奖|大礼包|秒杀|报名|投票|
    @RequestMapping("/api/order/miaosha")
    @ResponseBody
    public Jinfo miaosha(Order order,
                         @RequestParam(value = "leaid", required = false) Long leaid,
                         @RequestParam(value = "s", required = false) String scene,
                         @RequestParam(value = "o", required = false) String ori,
                         @RequestParam(value = "tmplIds", required = false) String tmplIds,
                         HttpServletRequest req) {
        logger.debug("---------------------------------------order/miaosha=" + JSON.toJSONString(order));
        logger.debug("---------------------------------------order/miaosha ori=" + ori);

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价

        Goods goods = goodsService.selectById(order.getGid());
        User user = redisService.getUser();
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>goods=" + goods);
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("请授权登录之后再操作");
            return json;
        }

        //生成订单
        Long uid = ObjectUtil.getUid();
        if (order.getType().intValue() != YXType.toupiao.getVal())
            order.setHeadimg(user.getAvatarPic());
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo("M"));//订单
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        order.setState(-1);
        order.setPrice(goods.getSaleprice());
        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);

//      ==========此类型活动特殊==========
        if (order.getType() == null) order.setType(YXType.miaosha.getVal());
        if (order.getType().intValue() == YXType.toupiao.getVal()) {
            order.setGoodsNumber(0);
        }
        if (order.getType().intValue() == YXType.choujiang.getVal()) {
            order.setGoodsNumber(1);
        }
        if (goods.getStores() != null && goods.getNumberSale() != null &&
                0 == goods.getStores().intValue()) {
            json.setCode(1);
            json.setMsg("当前参与人数已超出活动总人数");
            return json;
        }
        order.setStatus(order.getRealpay().doubleValue() > 0 ? 1 : 3);

        //
        //投票参与次数是否大于0
        if (order.getType().intValue() == YXType.toupiao.getVal()) {
            int cycout = orderService.selectCount(new EntityWrapper<Order>().eq("uid", uid).eq("gid", order.getGid()));
            if (cycout > 0) {
                json.setCode(1);
                json.setMsg("您已参与该活动");
                return json;
            }
        }
        if (order.getType().intValue() == YXType.toupiao.getVal()) {
            int tpcout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid()));
            order.setServiceCode(String.valueOf(tpcout + 1));//订单投票数
        }
//      ==========此类型活动特殊End==========

        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        if (goods.getLeagueid() != null) order.setLeagueid(goods.getLeagueid());
        if (leaid != null) order.setLeagueid(goods.getLeagueid());
        order.setHeadimg(user.getAvatarPic());
        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);
        MerchantConfig mconfig = redisService.getMconfig();
        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        logger.debug("-------------------------miaosha order.getShipperMethod()=" + order.getShipperMethod());
        logger.debug("-------------------------miaosha order.getGtype()=" + order.getGtype());
        logger.debug("-------------------------miaosha  store.getPstype()=" + store.getPstype());
        logger.debug("-------------------------miaosha  mconfig.getPstype()=" + mconfig.getPstype());
        if (pstype == null) pstype = store == null ? null : store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;//自提|到店|核销

        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                pstype = store.getPstype();
            } else {
                pstype = mconfig.getPstype();
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
        }
        order.setShipperMethod(pstype);
        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型
        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;

        //分享佣金计算
        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
            logger.debug("-------------------------cout=" + cout);
            logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
                sharefan = goods.getShareMount().multiply(num);
                sharefanj = sharefan;
            }
        }
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(new BigDecimal(order.getGoodsNumber()));
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(new BigDecimal(order.getGoodsNumber()));


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        //计算活动有效时常(单位：小时)
        if (goods.getTimeout() != null && goods.getTimeout().intValue() > 0) {
            order.setEndtime(DateUtil.addHour(order.getCreatetime(), goods.getTimeout().intValue()));
        }

        if (order.getType().intValue() == YXType.choujiang.getVal()) {
            order.setGoodsNumber(0);//等抽中奖品之后再累加商品
        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }
        //订单商品
        OrderGoods og = new OrderGoods();
        og.setGid(order.getGid());

        //普通分享奖励模式
        GoodsSku goodssku = null;
        if (order.getGid() != null && order.getGid() > 0) {
            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

        if (order.getId() == null) {
            order.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        }

        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        //======= 订单已支付后 =======
        //抽奖|大礼包|秒杀|报名|投票|
        logger.debug("============order=" + JSON.toJSONString(order));
        String title = order.getType() == YXType.choujiang.getVal() ? "在线支付抽奖活动" :
                order.getType() == YXType.miaosha.getVal() ? "在线支付秒杀活动" :
                        order.getType() == YXType.dalibao.getVal() ? "在线支付大礼包活动" :
                                order.getType() == YXType.baoming.getVal() ? "在线支付报名活动" :
                                        order.getType() == YXType.toupiao.getVal() ? "在线支付投票活动" : "在线支付参与活动";
        if (order.getRealpay().doubleValue() > 0) {
            json.setInfo(orderService.getPaymap(order, false, title));
        } else {
            logger.debug(">>>>order unprocess logic");
            //抽中之后变成3
            order.setStatus(order.getType().intValue() == YXType.choujiang.getVal()
                    || order.getType().intValue() == YXType.toupiao.getVal() ? 2 : 3);
            order.setPaytime(new Date());
            order.setState(1);
            order.setFhstate(1);
            order.updateById();

            Goods ngoods = new Goods();
            ngoods.setId(order.getGid());
            ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);

            logger.debug("=============================jizan order=" + JSON.toJSONString(order));
            if (order.getType().intValue() == YXType.toupiao.getVal() || order.getType().intValue() == YXType.jizan.getVal()) {
                ngoods.setNumberSale(goods.getNumberSale() + 1);
                ngoods.setStores(goods.getStores() - 1);
                logger.debug("=============================jizan ngoods=" + JSON.toJSONString(ngoods));
            } else if (order.getType().intValue() == YXType.choujiang.getVal()) {

            } else {
                ngoods.setNumberSale(goods.getNumberSale() == null ? order.getGoodsNumber() : order.getGoodsNumber() + goods.getNumberSale());
                ngoods.setStores(goods.getStores() - order.getGoodsNumber());
            }
            ngoods.setNumberOrders(goods.getNumberOrders() + 1);
            logger.debug("=============================before ngoods.updateById() ngoods=" + JSON.toJSONString(ngoods));
            ngoods.updateById();
            json.setExtra(order.getId());
        }

        return json;
    }

    //砍价接口
    @RequestMapping("/api/order/kanjiaopen")
    @ResponseBody
    public Jinfo kanjiaopen(Order order,
                            @RequestParam(value = "oid", required = false) Long oid,
                            @RequestParam(value = "ptoid", required = false) Long ptoid,
                            @RequestParam(value = "leaid", required = false) Long leaid,
                            @RequestParam(value = "s", required = false) String scene,
                            @RequestParam(value = "o", required = false) String ori,
                            @RequestParam(value = "tmplIds", required = false) String tmplIds,
                            HttpServletRequest req) {
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>order/kanjiaopen=" + JSON.toJSONString(order));
        logger.debug("---------------------------------------order/kanjiaopen tmplIds=" + tmplIds);

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价
        Goods goods = goodsService.selectById(order.getGid());

        User user = redisService.getUser();
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>realpay=" + realpay);
        logger.debug(">>>order=" + order);

        //生成订单
        Long uid = ObjectUtil.getUid();
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        order.setLeagueid(goods.getLeagueid());

        order.setOrderNo(StringUtil.getSnNo(""));//订单
        order.setState(1);
        order.setPrice(goods.getSaleprice());
        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);

        //订单来源
        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);
        order.setStatus(1);

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        if (leaid != null) order.setLeagueid(goods.getLeagueid());
        order.setHeadimg(user.getAvatarPic());
        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);

        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        if (pstype == null) pstype = store == null ? null : store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;//自提|到店|核销
        MerchantConfig mconfig = redisService.getMconfig();

        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                pstype = store.getPstype();
            } else {
                pstype = mconfig.getPstype();
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
        }
        order.setShipperMethod(pstype);

        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型
        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;
        boolean lianmeng = goods.getLeagueid() != null;

        //分享佣金计算
        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
            logger.debug("-------------------------cout=" + cout);
            logger.debug("-------------------------goods.getFenxiaoshu()=" + goods.getFenxiaoshu());
            //fenxiaoshu=null 分销奖励份数无限制
            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
                sharefan = goods.getShareMount().multiply(num);
                sharefanj = sharefan;
            }
        }
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(new BigDecimal(order.getGoodsNumber()));
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(new BigDecimal(order.getGoodsNumber()));


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        //计算活动有效时常(单位：小时)
        if (goods.getTimeout() != null && goods.getTimeout().intValue() > 0) {
            order.setEndtime(DateUtil.addHour(order.getCreatetime(), goods.getTimeout().intValue()));
        }

        //订单商品
        OrderGoods og = new OrderGoods();
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }
        og.setGid(order.getGid());

        GoodsSku goodssku = null;
        if (order.getSkuid() != null && order.getSkuid() > 0) {
            goodssku = goodsSkuService.selectById(order.getSkuid());
            og.setNumber(order.getGoodsNumber());
            og.setSaleprice(goodssku.getSaleprice());
            og.setPrice(goodssku.getPrice());
            og.setSpec(goodssku.getCharacteristic());

        } else if (order.getGid() != null && order.getGid() > 0) {

            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        //创建开团,订单支付成功之后再创建开团信息
        CutpriceOpen cutpriceOpen = null;
        if (ptoid == null) {
            cutpriceOpen = new CutpriceOpen();
            cutpriceOpen.setMid(order.getMid());
            cutpriceOpen.setMpid(order.getMpid());
            cutpriceOpen.setSid(order.getSid());
            cutpriceOpen.setGid(order.getGid());
            cutpriceOpen.setOid(order.getId());
            cutpriceOpen.setUid(order.getUid());

            cutpriceOpen.setGname(goods.getName());
            cutpriceOpen.setPic(goods.getPic());
            cutpriceOpen.setNickname(order.getLinkman());
            User ruser = redisService.getUser();
            cutpriceOpen.setAvatarpic(ruser.getAvatarPic());

            cutpriceOpen.setNumber(0);
            cutpriceOpen.setMinprice(goods.getSaleprice().add(order.getYunfei()));//低价
            cutpriceOpen.setPrice(goods.getPrice().add(order.getYunfei()));//当前价格
            cutpriceOpen.setCurprice(goods.getPrice().add(order.getYunfei()));//当前价格
            cutpriceOpen.setTotalcutPrice(new BigDecimal(0));//砍的总价格

            cutpriceOpen.setCreatetime(new Date());

            cutpriceOpen.setStatus(PTstatus.init.getVal());  //业务状态@1：进行中；2：拼团成功；0：拼团失败；
            cutpriceOpen.setStarttime(new Date());
//           cutpriceOpen.setEndtime(DateUtil.addDay(pintuanOpen.getStarttime(), goods.getTimeout()));//默认3天

            cutpriceOpen.insert();

            if (order.getSid() != null) {
                StoreStat storeStat = new StoreStat();
                storeStat.setStoreid(order.getSid());
                storeStat.setUsers(orderService.getHdCanyushu(order.getSid()));

                storeStat.setModifytime(new Date());
                storeStat.setMpid(order.getUid());

                storeStat.updateById();
            }
        }

        //======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));

        return json;
    }

    //砍价支付
    @RequestMapping("/api/order/kanjiapay")
    @ResponseBody
    public Jinfo kanjiapay(Long oid) {
        Jinfo info = new Jinfo();
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>order/kanjiapay oid=" + oid);
        CutpriceOpen cutpriceOpen = cutpriceOpenService.selectOne(new EntityWrapper<CutpriceOpen>()
                .eq("oid", oid));
        if (cutpriceOpen == null) {
            logger.info("-----------------cutpriceOpen is null for oid=" + oid);
            info.setCode(4);
            info.setMsg("订单不存在");
            return info;
        }
        Order order = orderService.selectById(oid);
        if (cutpriceOpen == null) {
            logger.info("-----------------cutpriceOpen is null for oid=" + oid);
            info.setCode(4);
            info.setMsg("订单不存在");
            return info;
        }
        Order norder = new Order();
        norder.setId(oid);
        norder.setOrderNo(StringUtil.getSnNo("K"));

        norder.setDiscount(order.getTotal().subtract(order.getRealpay()));
        norder.setModifytime(new Date());
        norder.setModifier(ObjectUtil.getUid());

        norder.updateById();
        order.setOrderNo(norder.getOrderNo());

        //======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));
        if (order.getRealpay().doubleValue() > 0) {
            info.setInfo(orderService.getPaymap(order, false, "在线支付砍价活动"));
        }

        return info;
    }

    //投票接口
    @RequestMapping("/api/order/toupiao")
    @ResponseBody
    public Jinfo toupiao(long oid) {
        Jinfo info = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("id", oid));
        if (order == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        order.setGoodsNumber(order.getGoodsNumber() + 1);
        order.setModifytime(new Date());
        order.setModifier(ObjectUtil.getUid());
        order.updateById();

        String tpdate = DateUtil.getToday();

        GoodsToupiao goodsToupiao = goodsToupiaoMapper.selectById(order.getGid());
        Integer piaoshu = toupiaoLogMapper.selectCount(new EntityWrapper<ToupiaoLog>()
                .eq("oid", oid)
                .eq("tpdate", tpdate)
                .eq("uid", ObjectUtil.getUid())
        );
        logger.debug("-------------------------------------piaoshu=" + piaoshu);
        logger.debug("-------------------------------------goodsToupiao.getDanripiao()=" + goodsToupiao.getDanripiao());
        if (goodsToupiao != null && goodsToupiao.getDanripiao() != null
                && piaoshu.intValue() >= goodsToupiao.getDanripiao().intValue()) {
            info.setCode(1);
            info.setMsg("当天已投票完，请明天再来投");
            return info;
        }

        ToupiaoLog toupiaoLog = new ToupiaoLog();
        toupiaoLog.setGid(order.getGid());
        toupiaoLog.setOid(order.getId());
        toupiaoLog.setTpdate(tpdate);
        toupiaoLog.setGid(order.getGid());
        toupiaoLog.setOid(order.getId());
        toupiaoLog.setTpdate(tpdate);

        User user = redisService.getUser();
        toupiaoLog.setMid(order.getMid());
        toupiaoLog.setMpid(order.getMpid());
        toupiaoLog.setSid(order.getSid());
        toupiaoLog.setUid(ObjectUtil.getUid());
        toupiaoLog.setAmount(1);

        toupiaoLog.setAvatarpic(user.getAvatarPic());
        toupiaoLog.setPhone(user.getPhone());
        toupiaoLog.setNickname(user.getNickName());
        toupiaoLog.insert();

        return info;
    }

    //集赞报名
    @RequestMapping("/api/order/jizanbm")
    @ResponseBody
    public Jinfo jizanbm(Order order,
                         @RequestParam(value = "leaid", required = false) Long leaid,
                         @RequestParam(value = "tmplIds", required = false) String tmplIds,
                         @RequestParam(value = "s", required = false) String scene,
                         @RequestParam(value = "o", required = false) String ori) {
        logger.debug("---------------------------------------order/jizanbm=" + JSON.toJSONString(order));
        Jinfo info = new Jinfo();
        Goods goods = goodsService.selectById(order.getGid());

        if (goods == null || goods.getState() != 1 || goods.getStatus() != 2) {
            info.setCode(1);
            info.setMsg("该集赞活动已失效，欢迎下次参与");
            return info;
        }

        int zanshu = orderService.selectCount(new EntityWrapper<Order>()
                .eq("gid", order.getGid())
                .eq("uid", ObjectUtil.getUid())
        );
        logger.debug("-------------------------------------zanshu=" + zanshu);
        if (goods.getXiangou() != null && zanshu >= goods.getXiangou()) {
            info.setCode(1);
            info.setMsg("每人只限参加" + goods.getXiangou() + "次该集赞活动");
            return info;
        }

        BigDecimal zero = new BigDecimal(0);

        User user = redisService.getUser();
        logger.debug(">>>order=" + order);

        //生成订单
        Long uid = ObjectUtil.getUid();
        if (order.getType().intValue() != YXType.toupiao.getVal())
            order.setHeadimg(user.getAvatarPic());
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo("M"));//订单
        order.setState(-1);

        if (order.getType() == null) order.setType(YXType.miaosha.getVal());
        if (order.getType().intValue() == YXType.toupiao.getVal()) {
            order.setGoodsNumber(0);
        }
        order.setPrice(goods.getSaleprice());
        order.setPrices(zero);
        order.setYunfei(zero);
        order.setTotal(zero);
        order.setRealpay(zero);

        //订单来源
        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);
        order.setStatus(order.getRealpay().doubleValue() > 0 ? 1 : 3);
        if (order.getRealpay().doubleValue() == 0) {
            order.setPaytime(new Date());
        }

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        if (goods.getLeagueid() != null) order.setLeagueid(goods.getLeagueid());
        if (leaid != null) order.setLeagueid(goods.getLeagueid());
        order.setHeadimg(user.getAvatarPic());
        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);


        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        if (pstype == null) pstype = store == null ? null : store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;//自提|到店|核销
        MerchantConfig mconfig = redisService.getMconfig();

        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                pstype = store.getPstype();
            } else {
                pstype = mconfig.getPstype();
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
        }
        order.setShipperMethod(pstype);

        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型
        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;
        boolean lianmeng = goods.getLeagueid() != null;

        //分享佣金计算
        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
            logger.debug("-------------------------cout=" + cout);
            logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
            //0表示不限制
            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
                sharefan = goods.getShareMount().multiply(num);
                sharefanj = sharefan;
            }
        }
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            // 非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(new BigDecimal(order.getGoodsNumber()));
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(new BigDecimal(order.getGoodsNumber()));


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        order.setGoodsNumber(1);
        if (order.getType().intValue() == YXType.toupiao.getVal()) {
            int tpcout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid()));
            order.setServiceCode(String.valueOf(tpcout + 1));
        }
        //计算活动有效时常(单位：小时)
        if (goods.getTimeout() != null && goods.getTimeout().intValue() > 0) {
            order.setEndtime(DateUtil.addHour(order.getCreatetime(), goods.getTimeout().intValue()));
        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }
        //订单商品
        OrderGoods og = new OrderGoods();

        og.setGid(order.getGid());

        //普通分享奖励模式
        GoodsSku goodssku = null;
        if (order.getGid() != null && order.getGid() > 0) {

            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

        if (order.getId() == null) {
            order.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        }

        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        //======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));

        JizanLog jizanLog = new JizanLog();
        jizanLog.setUid(order.getUid());
        jizanLog.setMid(order.getMid());
        jizanLog.setMpid(order.getMpid());
        jizanLog.setSid(order.getSid());

        jizanLog.setPtoid(order.getId());
        jizanLog.setGid(order.getGid());
        jizanLog.setOid(order.getId());

        jizanLog.setAvatarpic(user.getAvatarPic());
        jizanLog.setNickname(user.getNickName());
        jizanLog.setPhone(order.getPhone());
        jizanLog.setCreatetime(new Date());
        jizanLog.setState(1);
        jizanLog.setIsowner(1);
        jizanLog.insert();

        order.setStatus(2);
        order.setState(1);
        order.updateById();

        Goods ngoods = new Goods();
        ngoods.setId(order.getGid());
        ngoods.setCanyushu(goods.getCanyushu() + 1);
        ngoods.setNumberSale(goods.getNumberSale() + 1);
        ngoods.setNumberOrders(goods.getNumberOrders() + 1);
        ngoods.setStores(goods.getStores() - 1);
        ngoods.updateById();

        return info;
    }


    //他人点赞
    @RequestMapping("/api/order/dianzan")
    @ResponseBody
    public Jinfo dianzan(long oid) {
        Jinfo info = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("id", oid));
        if (order == null) {
            info.setCode(1);
            info.setMsg("该活动订单有误不存在");
            return info;
        }
        Goods goods = goodsService.selectById(order.getGid());
        if (goods == null) {
            info.setCode(1);
            info.setMsg("该活动不存在");
            return info;
        }

        int zanshu = jizanLogService.selectCount(new EntityWrapper<JizanLog>()
                .eq("oid", oid)
                .eq("uid", ObjectUtil.getUid())
        );
        logger.debug("-------------------------------------zanshu=" + zanshu);

        if (zanshu > 0) {
            info.setCode(1);
            info.setMsg("每人只有一次点赞机会，请转发他人帮忙集赞");
            return info;
        }

        int haszanshu = jizanLogService.selectCount(new EntityWrapper<JizanLog>()
                .eq("oid", oid));
        if (goods.getPtotal() <= haszanshu) {
            info.setCode(1);
            info.setMsg("该集赞活动已集满，谢谢下次参与");
            return info;
        }

        order.setGoodsNumber(order.getGoodsNumber() + 1);
        if (goods.getPtotal().intValue() == order.getGoodsNumber().intValue())
            order.setStatus(StatusEnum.receving.getVal());
        order.setModifytime(new Date());
        order.setModifier(ObjectUtil.getUid());
        order.updateById();

        JizanLog jizanLog = new JizanLog();
        jizanLog.setGid(order.getGid());
        jizanLog.setOid(order.getId());
        jizanLog.setPtoid(order.getId());
        jizanLog.setGid(order.getGid());

        User user = redisService.getUser();
        jizanLog.setMid(order.getMid());
        jizanLog.setMpid(order.getMpid());
        jizanLog.setSid(order.getSid());
        jizanLog.setUid(ObjectUtil.getUid());
        jizanLog.setIsowner(-1);
        jizanLog.setState(1);

        jizanLog.setAvatarpic(user.getAvatarPic());
        jizanLog.setPhone(user.getPhone());
        jizanLog.setNickname(user.getNickName());
        jizanLog.setCreatetime(new Date());
        jizanLog.insert();

        return info;
    }

    //投票搜索接口
    @RequestMapping("/api/order/tpsousuo")
    @ResponseBody
    public Jinfo tpsousuo(long gid, String serviceCode) {
        Jinfo info = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("gid", gid).eq("service_code", serviceCode));
        if (order == null) {
            info.setCode(1);
            info.setMsg("不存在该编号的报名用户");
            return info;
        }

        List<ToupiaoLog> list = toupiaoLogMapper.selectList(new EntityWrapper<ToupiaoLog>()
                .setSqlSelect("uid,avatarpic,nickname,phone,sum(amount) amount")
                .eq("oid", order.getId())
                .groupBy("uid,avatarpic,nickname,phone")
                .orderBy("amount", false));
        for (ToupiaoLog item : list) {
            item.setPhone(goodsService.replaceXing(item.getPhone()));
        }
        order.setTpusers(list);
        info.setInfo(order);

        return info;
    }

    @RequestMapping("/api/huodong/tpdetail")
    @ResponseBody
    public Jinfo tpdetail(long oid) {
        Jinfo info = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("id", oid));
        if (order == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        List<Order> plist = orderService.selectList(new EntityWrapper<Order>()
                .setSqlSelect("id,pic,linkman,phone,headimg,goods_number goodsNumber,remark,service_code serviceCode,extval1,extval1,gid")
                .eq("state", 1).eq("gid", order.getGid()).orderBy("goods_number", false));
        plist = goodsService.calcLastpiao(plist);
        Map<String, Order> map = goodsService.setlppmMap(plist);
        order = map.get("lppm" + order.getId());

        List<ToupiaoLog> list = toupiaoLogMapper.selectList(new EntityWrapper<ToupiaoLog>()
                .setSqlSelect("uid,avatarpic,nickname,phone,sum(amount) amount")
                .eq("oid", oid)
                .groupBy("uid,avatarpic,nickname,phone")
                .orderBy("amount", false));
        for (ToupiaoLog item : list) {
            item.setPhone(goodsService.replaceXing(item.getPhone()));
        }
        order.setTpusers(list);
        info.setInfo(order);

        return info;
    }

    //砍价帮砍，帮砍人可领取神秘礼品
    //领取神秘丽萍
    @RequestMapping("/api/order/lqsmliping")
    @ResponseBody
    public Jinfo lqsmliping(Order order,
                            @RequestParam(value = "leaid", required = false) Long leaid,
                            @RequestParam(value = "s", required = false) String scene,
                            @RequestParam(value = "o", required = false) String ori,
                            @RequestParam(value = "tmplIds", required = false) String tmplIds,
                            HttpServletRequest req) {
        logger.debug("---------------------------------------order/miaosha=" + JSON.toJSONString(order));

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价


        Goods goods = goodsService.selectById(order.getGid());
        User user = redisService.getUser();
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>goods=" + goods);
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("请授权登录之后再操作");
            return json;
        }

        Long uid = ObjectUtil.getUid();
        int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid",order.getGid()).eq("uid",uid));
        if (cout>0) {
            json.setCode(1);
            json.setMsg("该神秘礼品已领取");
            return json;
        }

        //生成订单
        order.setHeadimg(user.getAvatarPic());
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo());//订单
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        order.setState(1);
        order.setStatus(3);
        order.setPrice(goods.getSaleprice());
        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);
        order.setType(YXType.smliping.getVal());
        order.setPayType(PaytypeEnum.none.getVal());

        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);

        BigDecimal discount = new BigDecimal(0);
        //discount = 活动优惠+券优惠+积分优惠+会员优惠()
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }

        order.setDiscount(discount);//合计折扣
        order.setExpire(30);//默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        //记录联盟订单
        order.setSid(goods.getSid());
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (Strings.isNullOrEmpty(order.getAddress())) order.setAddress(store == null ? null : store.getAddress());
        if (goods.getLeagueid() != null) order.setLeagueid(goods.getLeagueid());
        if (leaid != null) order.setLeagueid(goods.getLeagueid());

        order.setPic(goods.getPic());
        order.setGtype(goods.getGtype());

        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        if (goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);
        }
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);

        int pstype = 4;
        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型
        //普通分享奖励
        BigDecimal sharefanj = zero;//返奖励
        BigDecimal sharefan = zero;//返现金佣金类型
        BigDecimal minprice = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;
        boolean lianmeng = goods.getLeagueid() != null;

        //分享佣金计算
//        if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
//                goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0) {
//            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
//                    .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
//            logger.debug("-------------------------cout=" + cout);
//            logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
//            if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue()) {
//                sharefan = goods.getShareMount().multiply(num);
//                sharefanj = sharefan;
//            }
//        }
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        if (goods.getShareBonusType() != null && goods.getShareBonusType() != XffanType.qian.getVal()) {
            sharefan = zero;//现金佣金
        }
        if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(num);
        if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(num);

        minprice = goods.getSaleprice().multiply(num).subtract(ptfan).subtract(lmfan).subtract(sharefan);

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);
        order.setMinprice(minprice);
        order.setPtfan(ptfan);
        order.setLmfan(lmfan);

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {

            if (goods.getShareMount() != null &&
                    goods.getShareMount().doubleValue() > 0 && sharefan.doubleValue() == 0) {
                order.setSharefan(sharefanj);
            }

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
            if (goods.getPtfan() != null) ptfan = goods.getPtfan().multiply(new BigDecimal(order.getGoodsNumber()));
            if (goods.getLmfan() != null) lmfan = goods.getLmfan().multiply(new BigDecimal(order.getGoodsNumber()));


        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }

        //计算活动有效时常(单位：小时)
//        if (goods.getTimeout() != null && goods.getTimeout().intValue() > 0) {
//            order.setEndtime(DateUtil.addHour(order.getCreatetime(), goods.getTimeout().intValue()));
//        }

        if (order.getType().intValue() == YXType.choujiang.getVal()) {
            order.setGoodsNumber(1);//等抽中奖品之后再累加商品
        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();

        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }
        //订单商品
        OrderGoods og = new OrderGoods();
        og.setGid(order.getGid());

        //普通分享奖励模式
        GoodsSku goodssku = null;
        if (order.getGid() != null && order.getGid() > 0) {
            og.setNumber(order.getGoodsNumber());
            og.setPrice(goods.getPrice());
            og.setSaleprice(goods.getSaleprice());
            og.setSpec(goods.getCharacteristic());
        }

        logger.debug(">>>og=" + JSON.toJSONString(og));

        og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
        og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
        og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
        og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

        if (order.getId() == null) {
            order.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        }

        og.setIsDefault(1);
        og.setStatus(order.getStatus());//订单状态
        og.setJifen(goods.getJifen());//订单状态
        og.setState(1);//订单状态
        og.setOrderType(1);
        og.setType(order.getType());

        og.setOid(order.getId());
        og.setGtype(goods.getGtype());

        og.setUid(order.getUid());
        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setOrderNo(order.getOrderNo());
        og.setCreatetime(order.getCreatetime());
        logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
        og.insert();

        //======= 订单已支付后 =======
        //神秘礼品
        logger.debug("============order=" + JSON.toJSONString(order));

        logger.debug(">>>>order unprocess logic");
        //抽中之后变成3
        order.setStatus(3);
        order.setState(1);
        order.setFhstate(1);
        order.updateById();

        Goods ngoods = new Goods();
        ngoods.setId(order.getGid());
        ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);

        ngoods.setNumberSale(goods.getNumberSale() == null ? order.getGoodsNumber() : order.getGoodsNumber() + goods.getNumberSale());
        if(goods.getStores()!=null)ngoods.setStores(goods.getStores() - order.getGoodsNumber());

        ngoods.setNumberOrders(goods.getNumberOrders() + 1);
        logger.debug("=============================before ngoods.updateById() ngoods=" + JSON.toJSONString(ngoods));
        ngoods.updateById();
        json.setExtra(order.getId());

        return json;
    }

}
